<?php
require_once('Extension/Controller/Action.php');

class SearchLuceneController extends Extension_Controller_Action 
{
    public function indexAction() 
    {
        $this->_forward('list');
    }

    public function listAction()
    {
        if ($this->getRequest()->isPost()) {
            
            $keywords = $this->_getParam('keywords', '');
            
            if (!empty($keywords)) {

                $luceneIndex = Kbs::initSearchLucene('open');

                $keywords = split(' ', trim($keywords));

                //$queryString = new Zend_Search_Lucene_Search_Query_Boolean();
                $queryString = new Zend_Search_Lucene_Search_Query_MultiTerm();

                foreach ($keywords as $keyword) {

                    /*
                    $term = new Zend_Search_Lucene_Index_Term('*' . $keyword . '*');
                    $subquery = new Zend_Search_Lucene_Search_Query_Wildcard($term);
                    $queryString->addSubquery($subquery, null);
                    */

                    $term = new Zend_Search_Lucene_Index_Term('*' . $keyword . '*');
                    $queryString->addTerm($term);
                }

                // input '\' to test this
                $query = Zend_Search_Lucene_Search_QueryParser::parse($queryString);

                echo 'your query : ' . $query . '<br />';

                $hits = $luceneIndex->find($query);

                $hitsResult = '';

                if (!$hits or empty($hits)) {
                    $hitsResult = $this->view->T('no results !');
                } else {
                    foreach ($hits as $hit) {
                        $document = $hit->getDocument();
                        //var_dump($document);
                        //$hitsResult .= '<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head>';
                        $hitsResult .= '<ul class="links">';
                        //$hitsResult .= '<li>Doc : ' . $hit->id . '</li>';
                        //$hitsResult .= '<li>score : ' . $hit->score . '</li>';
                        $hitsResult .= '<li><h3>' . $this->view->E($hit->post_title) . ' ( ' . $document->getFieldValue('post_date_create') . ' ) </h3></li>';
                        $hitsResult .= '<li>' . $document->post_content . '</li>';
                        $hitsResult .= '</ul>';
                    }
                }

                //$highlightedHitsResult = $query->highlightMatches($hitsResult);
                $highlightedHitsResult = $hitsResult;

                $this->view->hitsResult = $highlightedHitsResult;
            }
        }
    }
}